package com.hengxinguotong.zhihuichengjian.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.GroupGridAdapter;
import com.hengxinguotong.zhihuichengjian.bean.GroupDetailRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.CustomPatient;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/3/2.
 */

public class GroupActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.group_name_tv)
    HXTextView groupNameTv;
    @BindView(R.id.personnel_gv)
    GridView personnelGv;
    @BindView(R.id.delete_group_tv)
    HXTextView deleteGroupTv;
    @BindView(R.id.save_group)
    HXTextView saveGroup;
    private GroupGridAdapter groupGridAdapter;
    private String teamId;
    private String teamName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group);
        ButterKnife.bind(this);
        teamId = getIntent().getStringExtra("teamId");
        teamName = getIntent().getStringExtra("teamName");
        groupNameTv.setText(teamName);
        addListenter();
        getTeamDetail();
    }


    private void getTeamDetail() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("teamId", teamId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(getResources().getString(R.string.loading), this, "/team/queryTeamPersonList/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                Gson gson = new Gson();
                GroupDetailRes groupDetailRes = gson.fromJson(json, GroupDetailRes.class);
                groupGridAdapter = new GroupGridAdapter(GroupActivity.this, groupDetailRes.getValue(), hasEdit());
                personnelGv.setAdapter(groupGridAdapter);
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private void delPersonnel(String personId, final int position) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("personId", personId);
        params.addBodyParameter("teamId", teamId);
        Utils.requestData(getResources().getString(R.string.loading), this, "/team/deleteTeamPerson/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (groupGridAdapter == null) {
                    return;
                }
                groupGridAdapter.getUserInfos().remove(position);
                groupGridAdapter.notifyDataSetChanged();
                setResult(1);
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void addListenter() {

//        personnelGv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                if (!hasEdit()) {
//                    return false;
//                }
//
//                if (groupGridAdapter == null) {
//                    return false;
//                }
//                saveGroup.setVisibility(View.VISIBLE);
//                groupGridAdapter.setEdit(true);
//                groupGridAdapter.notifyDataSetChanged();
//                return false;
//            }
//        });

        personnelGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (groupGridAdapter == null) {
                    return;
                }
//                if (position == groupGridAdapter.getCount() - 1) {
//                    ActivityJumper.toAddGroupActivity(AddGroupActivity.EDITTYPE, GroupActivity.this, teamId, teamName);
//                    return;
//                }

//                if (groupGridAdapter.isEdit()) {
//                    showDelDialog(position);
//                } else {
                User user = (User) groupGridAdapter.getItem(position);
                Intent intent = new Intent(GroupActivity.this, AddPersonnelActivity.class);
                intent.putExtra("type", AddPersonnelActivity.MODTYPE);
                intent.putExtra("personId", user.getPersonId());
                startActivity(intent);
//                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1) {
            getTeamDetail();
            setResult(1);
        }
    }

    private void showDelDialog(final int position) {
        CustomPatient.Builder builder = new CustomPatient.Builder(this);
        builder.setContent("确定删除当前用户?", Utils.getTypeface(this), Utils.getTypeface(this));
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        User user = (User) groupGridAdapter.getItem(position);
                        delPersonnel(user.getPersonId(), position);
                        dialog.dismiss();
                    }
                });

        CustomPatient CustomPatient = builder.create();
        CustomPatient.show();
        Window window = CustomPatient.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.20); // 宽度设置为屏幕的0.20
        p.width = (int) (d.getWidth() * 0.70); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
    }


    @OnClick({R.id.iv_back, R.id.save_group})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_group:
                if (groupGridAdapter == null) {
                    return;
                }
                saveGroup.setVisibility(View.GONE);
                groupGridAdapter.setEdit(false);
                groupGridAdapter.notifyDataSetChanged();
                break;
        }
    }
}
